import requests

from util.authUtils.get_metabase_cookie import get_metabase_cookie
from util.otherutils.functions_control import get_data
from util.times_tool.time_control import count_time

headers = {"Cookie": f"metabase.DEVICE=31f6239e-85b3-4f0b-a924-7231c7935d22; metabase.SESSION={get_metabase_cookie()}"}
session = requests.session()


class MetabaseApi:

    @staticmethod
    @count_time
    def dataset(request_data):
        resp = session.post(url=f"http://metabase.vrviu.com/api/dataset",
                            headers=headers, json=request_data)
        if resp.status_code == 202:
            return resp.json()

    @staticmethod
    def get_cookie():
        url = f"http://metabase.vrviu.com/api/session"
        resp = session.post(url=url,
                            headers=headers,
                            json={"password": "Yf137422033@", "username": "frank.yan@cloudsky.com", "remember": True})
        if resp.status_code == 200:
            return resp.json().get('id')


if __name__ == '__main__':
    biz_id = 68
    flow_ids = ["4103_8gwainr27grr"]
    filter_flow_ids = [
                    "=",
                    [
                        "field",
                        8612,
                        None
                    ],
                    "4100_z3rt3hn6zhlw"
                ]
    filter_flow_ids.extend(flow_ids)
    data = {
        "database": 134,
        "parameters": [
        ],
        "query": {
            "aggregation": [
                [
                    "count"
                ]
            ],
            "breakout": [
                [
                    "field",
                    8612,
                    None
                ]
            ],
            "filter": [
                "and",
                [
                    "time-interval",
                    [
                        "field",
                        8618,
                        None
                    ],
                    0,
                    "day",
                    {
                        "include-current": None
                    }
                ],
                [
                    "=",
                    [
                        "field",
                        8609,
                        None
                    ],
                    str(biz_id)
                ],
                [
                    "=",
                    [
                        "field",
                        8566,
                        None
                    ],
                    1
                ],
                filter_flow_ids
            ],
            "source-table": 744
        },
        "type": "query"
    }
    resp = MetabaseApi.dataset(data)
    rows = resp.get('data').get('rows')
    fail_flow_id_list = list(map(lambda x: x[0], rows))
